package com.learning.spring.security.pwd.store.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * ClassName: SecurityConfig
 * Description: 密码存储
 * Date: 2022/7/29 9:14
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Configuration
public class InMemorySecurityConfig {

    /**
     * 1. 内存存储 InMemoryUserDetailsManager
     * - 内部使用 Map 存储用户对象
     * */


    /**
     * 密码存储基于内存实现
     * 密码是编码过的
     *
     * @return
     */
    @Bean
    public UserDetailsService inMemory() {
        // 创建 UserDetails
        UserDetails user = User.builder()
                .username("user")
                .password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW")
                .roles("USER")
                .build();
        UserDetails admin = User.withUsername("admin")
                .password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW")
                .roles("USER", "ADMIN")
                .build();

        return new InMemoryUserDetailsManager(user, admin);
    }

    /**
     * 密码存储基于内存实现
     *
     * @return
     */
    @Bean
    public UserDetailsService users() {
        // The builder will ensure the passwords are encoded before saving in memory
        User.UserBuilder users = User.withDefaultPasswordEncoder();
        UserDetails user = users
                .username("user")
                .password("password")
                .roles("USER")
                .build();
        UserDetails admin = users
                .username("admin")
                .password("password")
                .roles("USER", "ADMIN")
                .build();
        return new InMemoryUserDetailsManager(user, admin);
    }

}
